import { Component, OnInit} from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import {config} from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-authorize',
	templateUrl: './authorize.component.html',
})
export class AuthorizeComponent implements OnInit {
	page_title:string = '菜单';
	pageType:string = '';
	userId:string = '';//用户ID
	userName:string = '';//用户名
	curPage:number = 0;//缓存页码
	menuIds:any = [];
	companyCar:any = [];
	searchKey:string = '';//树形图查询关键字
	companyIds:any = [];//公司ID
	carSelectedIds:any = [];//车辆ID
	isShow:any = false;
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.userId = queryParams.id;
			this.pageType = queryParams.type;
			this.userName = queryParams.userName;
			this.curPage = queryParams.nowPage;

			if(common.getCookie('authorizeBackPath')){
				this.backPath = JSON.parse(common.getCookie('authorizeBackPath'));
				common.clearCookie('authorizeBackPath');
			}
		});
	}
	backPath: any = ''
	//tree  search功能
	table_search(){
		if(!this.searchKey){return;}
		$("#tree").jstree(true).search(this.searchKey);
		let searchResult = $('.jstree-search').length;
		if(searchResult < 1){
			this.jsonApiService.message('没有对应数据');
			return;
		}
		$('.jstree-search').each(function(index, obj) {
			if(index < 1) {//js树搜索定位到结果的第一个地方；
				var container = $('#tree_content'),
				scrollTo = $(this);
				container.scrollTop(scrollTo.offset().top - container.offset().top + container.scrollTop());
				container.animate({scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop() - $('#tree_content').height() * 0.3});
			}
		})
	}
	//展开tree
	allOpen(){
		$('#tree').jstree(true).open_all();
	}
	//折叠tree
	allClose(){
		$('#tree').jstree(true).close_all();
	}
	//初始化拉取数据(下拉列表)
	initdata() {
		var that = this;
		$('#tree').jstree({
				"core": {
					'data': function(obj, callback) {       
						var jsonstr = "[]";       
						var jsonarray = eval('(' + jsonstr + ')');
						var url = '';
						if(that.pageType === '菜单'){
							url = 'resource/resourceTreeSelectForUser.html';
							
						}else if(that.pageType === '车辆'){
							url = 'role/carTreeSelectForUser.html';
							
						}    
						$.ajax({        
								type: "GET",
						        url: config.BaseURL + url + "?userId=" + that.userId,
						        dataType: "json",
								xhrFields: {
									withCredentials: true
								},
						        success: function(data) {
									if(data.success == true){
										var result = data.data;
										this.companyCar = result;
										if(result.length == 0){
											this.isShow = true;
										}
										if(result.length<1){
											this.jsonApiService.message('该用户所属角色未分配'+that.pageType+'权限');
										}else{
											if(result[0].remark === 'company' || result[0].remark === 'car'){
												for(let i = 0; i < result.length; i++){
													if(result[i].state.selected && result[i].remark === 'company'){
														this.getChildren(result[i],i);//处理没有子级的选项状态
													}
												}
											}
										}
										jsonarray = this.companyCar;  
										callback.call(this, jsonarray);
									}
									
							}.bind(this)         
						});    
				}.bind(this),
				"themes": {
					"responsive": true
				},
				"multiple": true,
				"animation": 200,
				"dblclick_toggle": true,
				"expand_selected_onload": true
			},
			"checkbox": {
				"keep_selected_style": false,
				"three_state": true, //父子级别级联选择
				"cascade": "down"
			},
			"plugins": ["checkbox","search"]
		});
	}
	//遍历子级
	getChildren(val,i){
		for(let j = 0; j < this.companyCar.length; j++){
			if(val.id === this.companyCar[j].parent){
				this.companyCar[i].state.selected = false;
				break;
			}
		}
	}
	//获取所选子级的所有父级
	getParents(treeObj, nodeObj){
		var parentId = treeObj.get_parent(nodeObj);
		if(this.pageType === '车辆'){
			if(nodeObj.original.remark === 'company'&&!this.companyIds.includes(nodeObj.id)){
				this.companyIds.push(nodeObj.id);
			}else if(nodeObj.original.remark === 'car'){
				this.carSelectedIds.push(nodeObj.id);
				if(!this.companyIds.includes(nodeObj.parent)){
					this.companyIds.push(nodeObj.parent);
				}
			}
			if (parentId != "#") {
	            this.getParents(treeObj, treeObj.get_node(parentId));
	        }
		}
		else{
		 	if (parentId != "#") {
	        	if(!this.menuIds.includes(parentId)){
	        		this.menuIds.push(parentId);
	        	}
	            this.getParents(treeObj, treeObj.get_node(parentId));
	        }
		}
	}
	//权限数据保存
	saveDate(type){
		var url = '';
		var reqdata = '';
		this.menuIds = [];
		var tree = $('#tree').jstree();
        var selectedIds = tree.get_checked();   //获取所有选中节点id
        var selected = tree.get_checked(true);  //获取所有选中节点数据
        for (var i = 0; i < selected.length; i++) {
        	this.getParents(tree, selected[i]);
      	}
		if(this.pageType === '菜单'){
		 	let temResourceIds = new Set(selectedIds.concat(this.menuIds));   //合并去重
	        let resourceIds = Array.from(temResourceIds).join(',');  //Set转Array
	        if(!resourceIds){
	        	this.jsonApiService.message('至少分配一条菜单数据')
	        	return;
	        }
	        url = 'resource/updateResourcePermissionForUser.html';
	        reqdata = 'userId='+this.userId+'&resourceIds='+resourceIds+'&isFollow='+type;
		}else if(this.pageType === '车辆'){
	        let deviceIds = this.carSelectedIds.join(',');
	        if(!deviceIds){
	        	this.jsonApiService.message('至少分配一条车辆数据');
	        	return;
	        } 
	        url = 'role/updateCarPermissionForUser.html';
	        reqdata = 'userId='+this.userId+'&deviceIds='+deviceIds+'&isFollow='+type;
		}
	 	this.jsonApiService.http(url,reqdata).subscribe(data=> {
	 		this.jsonApiService.message(data.message);
        	if(data.success){
				this.router.navigate([this.backPath],{ queryParams: {nowPage:this.curPage}});
        	}
		})
	}
	goBack(){
		this.router.navigate([this.backPath],{ queryParams: {nowPage:this.curPage}});
	}
	ngOnInit() {
		System.import('assets/js/jstree/jstree.min.js').then(()=>{
			this.initdata();
		})
	}

}